package com.zxlfysj.huffmancode;

import java.io.*;
import java.util.*;

/**
 * 赫夫曼编码数据压缩
 *
 * @author yangshujing
 * @create 2020-08-20 11:38
 */
public class HuffmanCode {
    //map存放赫夫曼编码表
    static Map<Byte, String> huffmanCodes = new HashMap<>();
    //用于拼接路径
    static StringBuilder stringBuilder = new StringBuilder();

    public static void main(String[] args) {
        //String content = "i like like like java do you like a java";
        //byte[] contentBytes = content.getBytes();
        //测试赫夫曼编码数据压缩
        //byte[] huffmanCodesBytes = huffmanZip(contentBytes);
        //System.out.println(Arrays.toString(huffmanCodesBytes));
       // byteToBinaryString(true, (byte) -90);
        //测试解码
        //byte[] res = decode(huffmanCodes, huffmanCodesBytes);
        //System.out.println(new String(res));

        //测试压缩文件
        String srcFile = "d://src.bmp";
        String dstFIle = "d://dst.zip";
        zipFile(srcFile, dstFIle);

        //测试解压文件
        String zipFile = "d://dst.zip";
        String dstFile = "d://src1.bmp";
        unZipFile(zipFile, dstFile);

    }

    /**
     * 解压已经赫夫曼编码压缩的文件方法
     *
     * @param zipFile 准备解压的文件
     * @param dstFile 解压到目标文件
     */
    public static void unZipFile(String zipFile, String dstFile) {
        //定义文件输入流
        FileInputStream fileInputStream = null;
        //定义对象输入流
        ObjectInputStream ois = null;
        //定义文件输出流
        FileOutputStream fileOutputStream = null;

        try {
            //创建文件输入流
            fileInputStream = new FileInputStream(zipFile);
            //创建对象输入流
            ois = new ObjectInputStream(fileInputStream);
            //读取byte数组
            byte[] huffmanBytes = (byte[]) ois.readObject();

            //读取赫夫曼编码表
            Map<Byte, String> huffmanCodes = (Map<Byte, String>) ois.readObject();

            //解码
            byte[] bytes = decode(huffmanCodes, huffmanBytes);
            //将解码后得到的byte数组写入目标文件
            fileOutputStream = new FileOutputStream(dstFile);
            fileOutputStream.write(bytes);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {

            try {
                fileInputStream.close();
                fileOutputStream.close();
                ois.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }


    /**
     * 使用赫夫曼编码压缩文件方法
     *
     * @param srcFile 进行压缩的文件的路径
     * @param dstFile 压缩后存放的文件
     */
    public static void zipFile(String srcFile, String dstFile) {

        //创建文件的输入流
        FileInputStream fileInputStream = null;
        //创建文件的输出流
        FileOutputStream fileOutputStream = null;
        //创建对象输出流
        ObjectOutputStream oos = null;
        try {
            fileInputStream = new FileInputStream(srcFile);
            //创建和源文件一样大小的byte[]
            byte[] b = new byte[fileInputStream.available()];
            //读取文件
            fileInputStream.read(b);
            //使用赫夫曼编码进行压缩
            byte[] huffmanBytes = huffmanZip(b);
            //创建文件的输出流，存放压缩文件
            fileOutputStream = new FileOutputStream(dstFile);
            //创建对象输出流
            oos = new ObjectOutputStream(fileOutputStream);
            //以对象流的方式写入，方便以后解码
            oos.writeObject(huffmanBytes);
            //把赫夫曼编码表也写入
            oos.writeObject(huffmanCodes);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                fileInputStream.close();
                oos.close();
                fileOutputStream.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }


    }

    /**
     * 解码方法
     *
     * @param huffmanCodes      赫夫曼编码表
     * @param huffmanCodesBytes 要解码的字节数组
     * @return
     */
    private static byte[] decode(Map<Byte, String> huffmanCodes, byte[] huffmanCodesBytes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < huffmanCodesBytes.length; i++) {
            boolean flag = (i == huffmanCodesBytes.length - 1);  //最后一个不需要补高位
            stringBuilder.append(byteToBinaryString(!flag, huffmanCodesBytes[i]));
        }
        //赫夫曼编码表map，key和value调换，方便进行解码查询
        Map<String, Byte> map = new HashMap<>();
        for (Map.Entry<Byte, String> entry : huffmanCodes.entrySet()) {
            map.put(entry.getValue(), entry.getKey());
        }
        List<Byte> list = new ArrayList<>();
        for (int i = 0; i < stringBuilder.length(); ) {
            int count = 1;
            boolean flag = true;
            Byte b = null;
            while (flag) {
                //扫描stringBuilder，count为步长，匹配到map的一个，退出当前while
                //下一次for循环 i + count
                String key = stringBuilder.substring(i, i + count);
                b = map.get(key);
                if (b == null) {
                    count++;
                } else {
                    flag = false;
                }
            }
            list.add(b);
            i += count;
        }

        byte[] b = new byte[list.size()];
        for (int i = 0; i < b.length; i++) {
            b[i] = list.get(i);
        }
        return b;
    }

    //将一个byte字符 转成二进制的(8位)字符串
    //参数flag表示是否需要补高位，true表示需要补高位
    private static String byteToBinaryString(boolean flag, byte b) {
        int temp = b;
        //最后一个可能不满8位，不需要补高位
        if (flag) {
            temp |= 256;
        }
        String str = Integer.toBinaryString(temp); //返回的是temp的二进制补码
        if (flag) {
            return str.substring(str.length() - 8);
        } else {
            return str;
        }

    }

    private static byte[] huffmanZip(byte[] bytes) {
        //统计字符数组，按照字符次数为权重，得到Node集合
        List<Node> nodes = getNodes(bytes);
        //根据nodes创建赫夫曼树
        Node huffmanTreeRoot = createHuffmanTree(nodes);
        //根据赫夫曼树生成赫夫曼编码表
        Map<Byte, String> huffmanCodes = getCodes(huffmanTreeRoot);
        //将字符串对应的byte[]数组，通过赫夫曼编码表，生成压缩后的byte[] 数组
        byte[] huffmanCodesBytes = zip(bytes, huffmanCodes);
        return huffmanCodesBytes;

    }

    /**
     * 将字符串对应的byte[]数组，通过赫夫曼编码表，生成压缩后的byte[] 数组
     *
     * @param bytes        原始字符串的byte数组
     * @param huffmanCodes 赫夫曼编码表
     * @return
     */
    private static byte[] zip(byte[] bytes, Map<Byte, String> huffmanCodes) {

        StringBuilder stringBuilder = new StringBuilder();
        //利用赫夫曼编码表，将bytes转成对应的字符串
        for (byte b : bytes) {
            stringBuilder.append(huffmanCodes.get(b));
        }
        //将经过赫夫曼编码的字符串按8位一个字符，得到最终压缩字符长度，不能整除要多算一个长度
        int len = (stringBuilder.length() + 7) / 8;
        byte[] resBytes = new byte[len];
        int index = 0;
        for (int i = 0; i < stringBuilder.length(); i += 8) { //8位一个字符
            String strByte;
            if (i + 8 > stringBuilder.length()) { //最后一个不够8位
                strByte = stringBuilder.substring(i);
            } else {
                strByte = stringBuilder.substring(i, i + 8);
            }

            //将strByte转成一个byte
            resBytes[index] = (byte) Integer.parseInt(strByte, 2);
            index++;

        }
        return resBytes;
    }


    //重载根据赫夫曼树生成赫夫曼编码表方法，方便调用
    private static Map<Byte, String> getCodes(Node root) {
        if (root == null) {
            return null;
        }
        getCodes(root.left, "0", stringBuilder);
        getCodes(root.right, "1", stringBuilder);
        return huffmanCodes;
    }

    /**
     * 根据赫夫曼树生成赫夫曼编码表
     *
     * @param node          存入结点
     * @param code          路径：左子结点是0，右子结点1
     * @param stringBuilder 拼接路径
     */
    private static void getCodes(Node node, String code, StringBuilder stringBuilder) {
        StringBuilder stringBuilder2 = new StringBuilder(stringBuilder);
        stringBuilder2.append(code);
        if (node != null) {
            if (node.data == null) {  //非叶子结点
                //向左递归
                getCodes(node.left, "0", stringBuilder2);
                //向右递归
                getCodes(node.right, "1", stringBuilder2);
            } else { //叶子结点
                huffmanCodes.put(node.data, stringBuilder2.toString());
            }
        }
    }


    //前序遍历的方法
    private static void preOrder(Node root) {
        if (root != null) {
            root.preOrder();
        } else {
            System.out.println("空树无法遍历");
        }
    }

    //统计字符数组，按照次数为权重，创建Node集合
    private static List<Node> getNodes(byte[] bytes) {
        ArrayList<Node> nodes = new ArrayList<>();
        Map<Byte, Integer> counts = new HashMap<>();
        //遍历bytes数组，统计每一个字符出现的次数，然后存入map
        for (byte b : bytes) {
            Integer count = counts.get(b);
            if (count == null) {
                counts.put(b, 1);
            } else {
                counts.put(b, count + 1);
            }
        }
        //遍历map，按照key为data，value为weight，创建node()，加入nodes集合
        for (Map.Entry<Byte, Integer> entry : counts.entrySet()) {
            nodes.add(new Node(entry.getKey(), entry.getValue()));
        }
        return nodes;
    }

    //创建赫夫曼树
    public static Node createHuffmanTree(List<Node> nodes) {
        while (nodes.size() > 1) {
            //升序排序
            Collections.sort(nodes);
            //取出两个最小权值的结点组合成以权值之和为父节点的子树
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);
            Node parent = new Node(null, leftNode.weight + rightNode.weight);
            parent.left = leftNode;
            parent.right = rightNode;
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            nodes.add(parent);
        }
        return nodes.get(0);
    }
}

class Node implements Comparable<Node> {
    Byte data;
    int weight; //权值，表示字符出现的次数
    Node left;
    Node right;

    public Node(Byte data, int weight) {
        this.data = data;
        this.weight = weight;
    }

    //前序遍历
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    @Override
    public String toString() {
        return "Node{" +
                "data=" + data +
                ", weight=" + weight +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        return this.weight - o.weight;
    }
}
